/*
 * Class MixTexStuff
 * used for building/converting the tex files
 *
 */

package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

/**
 *
 * @author Suleyman Melikoglu
 */
public class MixTexStuff {

    public MixTexStuff(){

    }

    /**
     * Opens and reads the config.txt file and returns the absolute path of miktex program <br />
     * Returns filenotfound exception if there is no config.txt file <br />
     * Returns IOException if the file cannot be open <br />
     * Returns null otherwise <br />
     *
     * @return String
     */
    public String getMixTexPath(){
        try{
           FileReader fro = new FileReader( "config.txt" );
           BufferedReader bro = new BufferedReader( fro );

           // declare String variable and prime the read
           String stringFromFile = bro.readLine( );
           bro.close( );
           return stringFromFile;
        }catch( FileNotFoundException filenotfoundexxption ){
          System.out.println( "config.txt, does not exist" );
        }catch( IOException ioexception ){
          ioexception.printStackTrace( );
        }
        return null;
    }

    /**
     * convert the tex file to given format
     * this method is responsible for converting, vieweing and logging operations
     *
     * @param String program
     * @param JTextArea textAreaOutput for logging the messages
     * @param JTabbedPane tab_Editors
     * @return void
     */
    public void buildProcess(String program, JTextArea textAreaOutput, JTabbedPane tab_Editors ){
        try {

            TextEditors editors = new TextEditors();
            String filepath = editors.GetRealPath(tab_Editors.getSelectedIndex());
            String filename = editors.GetRealPathTitle(tab_Editors.getSelectedIndex());

            textAreaOutput.append("\n-----------");

            //get rid of the extension
            int whereDot = filename.lastIndexOf('.');
            if (0 < whereDot && whereDot <= filename.length() - 2 ) {
                filename = filename.substring(0, whereDot);
                //extension = filename.substring(whereDot+1);
            }

            String outputPath = filepath;
            //get rid of the filename and extension
            int whereFilename = outputPath.lastIndexOf("\\");
            if (0 < whereFilename && whereFilename <= outputPath.length() - 2 ) {
                outputPath = outputPath.substring(0, whereFilename);
            }

            String cmd;
            Process p;
            if(program.equalsIgnoreCase("dvips.exe")){
                //convert to dvi first
                String cmdTemp = "cmd /C " + this.getMixTexPath() + "latex.exe " +
                    filepath + " -output-directory=" +
                    outputPath + " -job-name=" + filename + " -quiet";
                // then convert the dvi to ps file
                this._buildHelper( Runtime.getRuntime().exec( cmdTemp ) );

                
                cmd = "cmd /C " + this.getMixTexPath() + "dvips -f " +
                    outputPath + "\\" + filename + ".dvi -o " +
                    outputPath + "\\" + filename + ".ps -quiet";
                // then convert the dvi to ps file
                p = Runtime.getRuntime().exec( cmd );
            }else{
                cmd = "cmd /C " + this.getMixTexPath() + program + " " +
                    filepath + " -output-directory=" +
                    outputPath + " -job-name=" + filename + " -quiet";
                p = Runtime.getRuntime().exec( cmd );
                
            }
           

            //textAreaOutput.append("Command: \n" + cmd);
            

            textAreaOutput.append("\nAction Start \n");
            this._buildHelper(p);
            

           // force to open the file
            try{
                 String os = System.getProperty("os.name");
                // if the os is windows, then view the file with system's default
                if(os.contains("Windows")){
                    if(program.equalsIgnoreCase("latex.exe")){
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".dvi");   //open the file chart.pdf
                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".dvi");
                    }else if(program.equalsIgnoreCase("pdflatex.exe")){
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".pdf");   //open the file chart.pdf
                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".pdf");
                    }else if(program.equalsIgnoreCase("dvips.exe")){
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".ps");   //open the file chart.pdf
                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".ps");
                    }
                }else{
                    //it is not windows. so inform the user that we cannot provide a viewer, go and get a windows machine buddy.
                    textAreaOutput.setText("\nFiles are processed successfully, However we do not support your operation system for viewing those files.");
                }
                textAreaOutput.append("\nOperation successful!");
            }catch (Exception e){
                 //JOptionPane.showMessageDialog(null,"Cannot open the file!","Error",JOptionPane.ERROR_MESSAGE);
                textAreaOutput.append("\nCannot open the file!");
            }

        } catch (IOException ex) {
            //Logger.getLogger(OpenTexEditorView.class.getName()).log(Level.SEVERE, null, ex);
            //JOptionPane.showMessageDialog(null,"Cannot complete the request!","Error",JOptionPane.ERROR_MESSAGE);
            textAreaOutput.append("\nCannot complete the request \n");
        }
    }

    private void _buildHelper(Process p){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            long t1;
            while ((line = in.readLine()) != null) {
                t1 = System.currentTimeMillis();
                if (t1 > 1000000) {
                    //JOptionPane.showMessageDialog(null,"Cannot compile the file!","Compile error",JOptionPane.ERROR_MESSAGE);
                    //break;
                }
                //textAreaOutput.append(line);
            }
        } catch (IOException ex) {
            Logger.getLogger(MixTexStuff.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getFileNameWithoutExtension(String fileName) {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {
            return tmpFile.getName().substring(0, whereDot);
            //extension = filename.substring(whereDot+1);
        }
        return "";
    }


}
